package jhc.cn.servlet;

import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jhc.cn.AirSpace;

/**
 * Servlet implementation class VcodeServlet
 */
@WebServlet("/vcode")
public class VCode extends HttpServlet implements AirSpace {

	public static int randomIntMac(int x,int y) {
		Random random = new Random();
		int rando = random.nextInt(y - x) + x;
    		return rando; 
	}



	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("image/png");
		String vcodeValue = "";
		char word;
		int x = 20, y = 40;
		BufferedImage bIamge = new BufferedImage(150, 50, BufferedImage.TYPE_INT_RGB);
		Graphics2D ggGraphics2d = bIamge.createGraphics();
		for (int i = 0; i < 5; i++) {
			word = (char) randomIntMac(65, 90);
			String str = String.valueOf(word);
			ggGraphics2d.setFont(new Font(null, randomIntMac(0, 5), randomIntMac(28, 42)));
			ggGraphics2d.rotate(randomIntMac(0, 7)/10);
			ggGraphics2d.drawString(str, x, y);
			vcodeValue += str;
			ggGraphics2d.drawLine(randomIntMac(0, 10), randomIntMac(0, 80), randomIntMac(190, 200), randomIntMac(0, 80));
			x = x + 22;
			y = y + randomIntMac(-3, 3);
		}
		x = 20;
		y = 40;
		ImageIO.write(bIamge, "png", response.getOutputStream());
		
		request.getSession().setAttribute(VCODE_KEY, vcodeValue);
	}

}
